package org.swxjava.locator;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContextUtils;

import org.swxjava.WebContextFactory;
import org.swxjava.util.Log;
import org.swxjava.util.LogFactory;
import org.swxjava.util.MessageBundle;

public class SpringServiceLocator implements ServiceLocator {

	/** Logger */
	private static final Log LOG = LogFactory
			.getLog(SpringServiceLocator.class);

	private String beanName = null;

	private BeanFactory factory = null;

	public Object getInstance() throws InstantiationException {
		try {
			if (factory == null) {
				factory = getBeanFactory();
			}
			if (factory == null) {
				LOG.error("SWX Java can't find a spring config. See following info logs for solutions");
				LOG.info("- Use a spring org.springframework.web.context.ContextLoaderListener.");
				throw new InstantiationException(MessageBundle.getString("SpringServiceLocator.MissingConfig"));
			}

			return factory.getBean(beanName);
		} catch (RuntimeException ex) {
			throw ex;
		} catch (Exception ex) {
			LOG.error("Error", ex);
			throw new InstantiationException(ex.toString());
		}
	}

	private BeanFactory getBeanFactory() {
		ServletContext srvCtx = WebContextFactory.get().getServletContext();
		HttpServletRequest request = WebContextFactory.get()
				.getHttpServletRequest();

		if (request != null) {
			return RequestContextUtils
					.getWebApplicationContext(request, srvCtx);
		} else {
			return WebApplicationContextUtils.getWebApplicationContext(srvCtx);
		}
	}

	public String getBeanName() {
		return beanName;
	}

	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}
}
